package com.gegao.chat_test;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

public class WebSocketClient implements Runnable {
    private static Channel conChannel = null;
    private String uid = "2";
    private String ticket = "3e4d77894ad64ab51fc561b9224d792e";
    private String path = "192.168.1.29";
    private String port = "1234";
    private ClientBootstrap bootstarp = null;
    private int sendInterval;
    private int threadId;

    public WebSocketClient(String uid, String ticket, String path, String port) {
        this.uid = uid;
        this.ticket = ticket;
        this.path = path;
        this.port = port;
    }

    public WebSocketClient(int threadId, int sendInterval) {
        this.threadId = threadId;
        this.sendInterval = sendInterval;
    }

    @Override
    public void run() {
        URI uri = null;
        try {
            uri = new URI("ws://54.254.147.35:8899/?debug=" + threadId);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
//            uri = new URI("ws://" + path + ":" + this.port + "/?U=" + uid + ",T=" + ticket);
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
        Map<String, String> customHeaders = new HashMap<>();
        customHeaders.put("MyHeader", "MyValue");
        Channel ch;
        final WebSocketClientHandshaker handshaker = new WebSocketClientHandshakerFactory().newHandshaker(uri,
                WebSocketVersion.V13, null, false, customHeaders);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decoder", new HttpResponseDecoder());
                pipeline.addLast("encoder", new HttpRequestEncoder());
                pipeline.addLast("ws-handler", new WebSocketClientHandler(handshaker, threadId, sendInterval));
                return pipeline;
            }

        });

        // Connect.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("54.254.147.35", 8899));
        try {
            ch = future.sync().getChannel();
            conChannel = ch;
            handshaker.handshake(ch).sync();
            Thread t = new Thread(new chatSendThread());
            t.setDaemon(false);
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if (bootstarp != null) {
            bootstarp.shutdown();
        }
    }

    class chatSendThread implements Runnable {
        @Override
        public void run() {
            while (ClientTester.activityThread.get() < 5) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                int uid = (int) (Math.random() * ClientTester.activityThread.get());
                while (uid == 0 || uid == threadId) {
                    uid = (int) (Math.random() * ClientTester.activityThread.get());
                }
                String content = "{\"method\":\"sendmessage\",\"content\":{\"type\":\"TEXT\",\"text\":\"你好，朋友\"},\"uid\":" + threadId + ",\"touid\":" + uid + ",\"clientdate\":1452749048304}";
                sendMsg(content);

                Thread.sleep(sendInterval * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMsg(final String content) {
        try {
            if (conChannel == null) {
                System.out.println("客户端未连接服务器");
            }
            conChannel.write(new TextWebSocketFrame(content));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("线程:" + this.threadId + "会话被关闭！！！！！！！！！！！！");
        }
    }

//    public static void main(String[] args) {
//        Scanner scanner = new Scanner(System.in);
//        System.out.println("是否需要自定义(Y/N)");
//        WebSocketClient client;
//        if (scanner.nextLine().equalsIgnoreCase("n")) {
//            client = new WebSocketClient();
//        } else {
//            System.out.println("请输入服务器IP");
//            String path = scanner.nextLine();
//            while (null == path || path.length() == 0) {
//                System.out.println("请输入服务器IP");
//                path = scanner.nextLine();
//            }
//            System.out.println("请输入服务器端口");
//            String port = scanner.nextLine();
//            while (null == port || port.length() == 0) {
//                System.out.println("请输入服务器端口");
//                port = scanner.nextLine();
//            }
//            System.out.println("请输入用户id");
//            String uid = scanner.nextLine();
//            while (null == uid || uid.length() == 0) {
//                System.out.println("请输入用户id");
//                uid = scanner.nextLine();
//            }
//            System.out.println("请输入用户ticket");
//            String ticket = scanner.nextLine();
//            while (null == ticket || ticket.length() == 0) {
//                System.out.println("请输入用户ticket");
//                ticket = scanner.nextLine();
//            }
//            client = new WebSocketClient(uid, ticket, path, port);
//        }
//        client.run();
//        System.out.println("请输入需要传送的JSON格式文本,输入quit退出连接");
//        while (true) {
//            String content = scanner.nextLine();
//            if (content.equals("quit")) {
//                break;
//            }
//            client.sendMsg(content);
//        }
//        client.close();
//        scanner.close();
//    }

}
